<template>
    <div class="company-list" style="height: 100%;" v-loading="loading" element-loading-text="Loading..."
        element-loading-background="rgba(122, 122, 122, 0.1)">
        <div class="search-bar">
            <CompanyAutoInput style="margin-right:1rem;" @select="handleSelect"></CompanyAutoInput>
            <el-button type="primary" @click="resetFields" class="reset-button">重置</el-button>
            <el-button type="primary" @click="addCompany" class="add-button">新增公司</el-button>
        </div>
        <div class="company-cards">
            <el-empty v-if="!companyList?.length && !loading" description="暂无数据" style="width: 100%; height: 100%;">
            </el-empty>
            <el-card v-else v-for="company in companyList" :key="company.id" class="company-card" shadow="hover"
                @click="goToCompanyDetail(company.id)">
                <template #header>
                    <el-tag :type="company.status === 1 ? 'success' : 'danger'" class="status-tag" effect="plain"
                        size="small">
                        {{ company.status === 1 ? '在用' : '停用' }}
                    </el-tag>
                    <el-icon class="settings-icon" size="1.4rem" @click.stop="editCompany(company)">
                        <Setting />
                    </el-icon>
                </template>
                <div class="card-body">
                    <h3>{{ company.name }}</h3>
                    <p class="company-sector">{{ company.sector || '暂无' }}</p>
                    <div class="time-info">
                        <span>创建：{{ formatDate(company.created_at) }}</span>
                        <span>更新：{{ formatDate(company.updated_at) }}</span>
                    </div>
                </div>
            </el-card>
        </div>

        <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize"
            :total="total" :hide-on-single-page="true" background :pager-count="5" layout="prev, pager, next"
            class="pagination"></el-pagination>
    </div>
    <el-dialog class="company-dialog" :title="currentCompany ? '编辑公司' : '新增公司'" align-center v-model="dialogVisible">
        <CompanyDialog @fetch-company-list="fetchCompanyList" :id="currentCompany"></CompanyDialog>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Setting } from '@element-plus/icons-vue';
import { getCompanyListApi } from '@/api/company';
import { formatDate } from '@/utils/date';
import CompanyDialog from './components/CompanyDialog.vue';
import CompanyAutoInput from './components/CompanyAutoInput.vue';

let router = useRouter();
let searchKeyword = ref('');
let selectedStatus = ref('');
let selectedSector = ref('');
let selectedProduct = ref('');
let companyList = ref([]);
let currentPage = ref(1);
let pageSize = ref(20);
let total = ref(0);
let sectorOptions = ref([]);
let productOptions = ref([]);
let dialogVisible = ref(false);
let currentCompany = ref(null);
let loading = ref(false);

const resetFields = () => {
    searchKeyword.value = '';
    selectedStatus.value = '';
    selectedSector.value = '';
    selectedProduct.value = '';
    fetchCompanyList();
};

onMounted(() => {
    fetchCompanyList();
});

const fetchCompanyList = () => {
    loading.value = true;
    currentCompany.value = null;
    dialogVisible.value = false;
    const params = {
        offset: pageSize.value * (currentPage.value - 1),
        limit: pageSize.value,
        name: searchKeyword.value,
        status: selectedStatus.value,
        sector: selectedSector.value,
        product_name: selectedProduct.value,
    };

    getCompanyListApi(params).then((res) => {
        if (res.code === 200) {
            companyList.value = res.data.companies;
            sectorOptions.value = res.available_list.sector;
            productOptions.value = res.available_list.product_name;
            total.value = res.data.total;
        } else {
            showErrorNotification('获取公司列表失败', res.message);
        }
    }).catch((err) => {
        showErrorNotification('获取公司列表失败', err.message);
    }).finally(() => {
        loading.value = false;
    });
};

const showErrorNotification = (title, message) => {
    ElNotification({
        title: title,
        message: message || '操作失败，请稍后重试',
        type: 'error',
        duration: 5000,
        position: 'top-right'
    });
};

function handleSelect(company) {
    searchKeyword.value = company.name;
    fetchCompanyList();
}

const addCompany = () => {
    currentCompany.value = null;
    router.push({ name: 'MapSelector', query: { from: 'CompanyList' } })
};

const editCompany = (company) => {
    currentCompany.value = company.id;
    dialogVisible.value = true;
};

const goToCompanyDetail = (companyId) => {
    router.push({ name: 'CompanyDetail', query: { id: companyId } });
};

const handlePageChange = (page) => {
    currentPage.value = page;
    fetchCompanyList();
};
</script>

<style scoped>
.company-list {
    padding: 2rem;
    height: 100%;
    width: 100%;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 1.25rem;
    gap: 0.625rem;
}

.status-select {
    width: 7.5rem;
}

.sector-select,
.product-select {
    width: 10rem;
}

.add-button {
    margin-left: auto;
}

.company-cards {
    height: 85%;
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
}

.company-card {
    width: calc(20% - 1.2rem);
    height: 200px;
    /* 设置固定高度 */
    cursor: pointer;
    transition: all 0.3s;
}


.company-card :deep(.el-card__header) {
    padding: 0.75rem 1rem;
}

.company-card :deep(.el-card__body) {
    padding: 1rem;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.settings-icon {
    color: #909399;
    cursor: pointer;
    transition: color 0.3s;
}

.settings-icon:hover {
    color: #409EFF;
}

.card-body h3 {
    margin: 0 0 0.5rem 0;
    font-size: 1.1rem;
    font-weight: 600;
    color: #303133;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.company-sector {
    font-size: 0.9rem;
    color: #606266;
    text-align: center;
    margin-bottom: 0.75rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.card-body {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-height: 0;
    /* 确保flex-shrink生效 */
}

.time-info {
    font-size: 0.75rem;
    color: #909399;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.25rem;
}

.pagination {
    margin-top: 1.25rem;
    text-align: center;
    padding: 1rem 0;
}

@media screen and (max-width: 1400px) {
    .company-card {
        width: calc(25% - 1.2rem);
    }
}

@media screen and (max-width: 1200px) {
    .company-card {
        width: calc(33.333% - 1.2rem);
    }
}

@media screen and (max-width: 768px) {
    .company-list {
        padding: 1rem;
    }

    .search-bar {
        flex-wrap: wrap;
    }

    .status-select,
    .sector-select,
    .product-select {
        width: calc(50% - 0.625rem);
    }

    .company-card {
        width: calc(50% - 1rem);
    }

    .add-button,
    .reset-button {
        width: calc(50% - 0.625rem);
        margin: 0.625rem 0 0 0;
    }
}

@media screen and (max-width: 480px) {
    .company-list {
        padding: 0.5rem;
    }

    .company-card {
        width: 100%;
    }

    .status-select,
    .sector-select,
    .product-select,
    .add-button,
    .reset-button {
        width: 100%;
    }
}
</style>